package com.jkoss.biz.imp;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.jkoss.biz.IEmpsBiz;
import com.jkoss.dao.jy.StuattendanceMapper;
import com.jkoss.dao.oa.DepartmentMapper;
import com.jkoss.dao.oa.EmpattendanceMapper;
import com.jkoss.dao.oa.EmpfilesMapper;
import com.jkoss.dao.oa.EmpqinjiaMapper;
import com.jkoss.dao.oa.OssqqMapper;
import com.jkoss.dao.oa.SalaryMapper;
import com.jkoss.dao.stu.OssstuMapper;
import com.jkoss.pojo.jy.Stuattendance;
import com.jkoss.pojo.oa.Department;
import com.jkoss.pojo.oa.EmpJobs;
import com.jkoss.pojo.oa.EmpJobsExample;
import com.jkoss.pojo.oa.Empattendance;
import com.jkoss.pojo.oa.Empfiles;
import com.jkoss.pojo.oa.EmpfilesExample;
import com.jkoss.pojo.oa.Empqinjia;
import com.jkoss.pojo.oa.Emps;
import com.jkoss.pojo.oa.Ossqq;
import com.jkoss.pojo.oa.Salary;
import com.jkoss.tool.DbCommonMethod;
import com.jkoss.tool.Page;

@Component
public class EmpsBiz implements IEmpsBiz {

	@Autowired
	private com.jkoss.dao.oa.EmpsMapper edao;
	@Autowired
	private com.jkoss.dao.oa.DepartmentMapper ddao;
	@Autowired
	private com.jkoss.dao.oa.EmpJobsMapper jbdao;
	@Autowired
	private EmpfilesMapper efdao;
	@Autowired
	private OssqqMapper eqqDao;
	@Autowired
	private SalaryMapper salDao;
	@Autowired
	private OssstuMapper stuDao;
	@Autowired
	private StuattendanceMapper stuKqinDao;
	@Autowired
	private DepartmentMapper deptDao;
	@Autowired
	private EmpattendanceMapper empKqinDao;
	@Autowired
	private EmpqinjiaMapper empQJDao;

	// 登录
	public Emps login(Emps e) {
		Emps tmp = edao.selectByLgnName(e.getLgnName());
		if (tmp != null && tmp.getPwdword().equals(e.getPwdword())) {
			return tmp;
		}
		return null;
	}

	public List<Department> listPageDepts(Page<Department> page) {
		return ddao.selectAtPage(page);
	}

	@Transactional
	public String addDept(Department dept) {
		// TODO Auto-generated method stub
		return ddao.insert(dept) > 0 ? "添加成功" : "添加失败";
	}

	@Override
	public Department findDeptByID(int did) {
		// TODO Auto-generated method stub
		return ddao.selectByPrimaryKey(did);
	}

	@Override
	@Transactional
	public String updtDept(Department dept) {
		return ddao.updateByPrimaryKey(dept) > 0 ? "更新成功" : "更新失败";
	}

	@Override
	@Transactional
	public String deleteDept(int depID) {
		return ddao.deleteByPrimaryKey(depID) > 0 ? "删除成功" : "删除失败";
	}

	@Override
	public List<Department> listDepts() {
		// TODO Auto-generated method stub
		return ddao.selectByExample(null);
	}

	@Override
	public List<EmpJobs> findJobsByDid(int did) {
		// TODO Auto-generated method stub
		EmpJobsExample ejb = null;
		if (did > 0) {
			ejb = new EmpJobsExample();
			ejb.createCriteria().andDepIDEqualTo(did);
		}
		return jbdao.selectByExample(ejb);
	}

	@Override
	@Transactional
	public String addJob(EmpJobs jb) {
		// TODO Auto-generated method stub
		return jbdao.insert(jb) > 0 ? "添加成功" : "添加失败";
	}

	@Override
	public EmpJobs findJobByID(int jbid) {
		// TODO Auto-generated method stub
		return jbdao.selectByPrimaryKey(jbid);
	}

	@Override
	@Transactional
	public String updtJobs(EmpJobs job) {
		// TODO Auto-generated method stub
		return jbdao.updateByPrimaryKey(job) > 0 ? "更新成功" : "更新失败";
	}

	@Override
	@Transactional
	public String deleteJobs(int jbid) {
		// TODO Auto-generated method stub
		return jbdao.deleteByPrimaryKey(jbid) > 0 ? "删除成功" : "删除失败";
	}

	@Override
	@Transactional
	public String addEmp(Emps emp) {
		// TODO Auto-generated method stub
		return edao.insert(emp) > 0 ? "添加成功" : "添加失败";
	}

	// 员工全部信息
	@Override
	public List<Emps> findAllEmp() {

		return edao.findAllEmp();
	}

	@Override
	public Emps findEmpByID(int eid) {
		// TODO Auto-generated method stub
		return edao.selectByPrimaryKey(eid);
	}

	@Override
	public List<Emps> listPageEmps(Page<Emps> page) {
		// TODO Auto-generated method stub
		return edao.selectAtPage(page);
	}

	@Override
	@Transactional
	public String updtEmp(Emps emp) {
		// TODO Auto-generated method stub
		return edao.updateByPrimaryKey(emp) > 0 ? "更新成功" : "更新失败";
	}

	@Override
	@Transactional
	public String deleteEmps(int eid) {
		return edao.deleteByPrimaryKey(eid) > 0 ? "删除成功" : "删除失败";
	}

	@Override
	public List<Emps> listDptEmps(int did) {
		// TODO Auto-generated method stub
		return edao.selectEmpsByDpt(did);
	}

	@Override
	@Transactional
	public String addEmpfiles(Empfiles file) {
		// TODO Auto-generated method stub
		return efdao.insert(file) > 0 ? "添加成功" : "添加失败";
	}

	@Override
	public Empfiles findEmpfilesByID(int efid) {
		// TODO Auto-generated method stub
		return efdao.selectByPrimaryKey(efid);
	}

	@Override
	public List<Empfiles> listEmpfilesByEmp(int eid, String fn) {
		// TODO Auto-generated method stub
		EmpfilesExample e = new EmpfilesExample();

		if (fn != null) {
			e.createCriteria().andT_e_eidEqualTo(eid).andFjnameLike(fn);
		} else {
			e.createCriteria().andT_e_eidEqualTo(eid);
		}
		return efdao.selectByExample(e);
	}

	@Override
	@Transactional
	public String deleteEmpfiles(int fjid) {
		// TODO Auto-generated method stub
		return efdao.deleteByPrimaryKey(fjid) > 0 ? "删除成功" : "删除失败";
	}

	//////////////////////// 企业qq管理
	@Override
	public List<Ossqq> listPageOssqqs(Page<Ossqq> page) {
		// TODO Auto-generated method stub
		List<Ossqq> datas = eqqDao.selectAtPage(page);
		if (datas != null) {
			for (Ossqq ossqq : datas) {
				if (ossqq.getEid() != null)
					ossqq.setOwner(findEmpByID(ossqq.getEid()));
				if (ossqq.getT_e_eid() != null)
					ossqq.setUseEmp(findEmpByID(ossqq.getT_e_eid()));
			}
		}
		return datas;
	}

	@Override
	@Transactional
	public String addOssqq(Ossqq jb) {
		// TODO Auto-generated method stub
		return eqqDao.insert(jb) > 0 ? "添加成功" : "添加失败";
	}

	@Override
	public Ossqq findOssqqByID(int qqeid) {
		// TODO Auto-generated method stub
		return eqqDao.selectByPrimaryKey(qqeid);
	}

	@Override
	@Transactional
	public String deleteOssqq(int qqeid) {
		// TODO Auto-generated method stub
		return eqqDao.deleteByPrimaryKey(qqeid) > 0 ? "删除成功" : "删除失败";
	}

	@Override
	@Transactional
	public String updtOssqq(Ossqq eqq) {
		// TODO Auto-generated method stub
		return eqqDao.updateByPrimaryKey(eqq) > 0 ? "更新成功" : "更新失败";
	}

	@Override
	public Ossqq findOssqqByName(String qqname) {
		// TODO Auto-generated method stub
		return eqqDao.selectByEqename(qqname);
	}

	@Override
	@Transactional
	public String changeEqqUser(int qqeid, int eid) {
		// 取得Eqq
		Ossqq eqq = findOssqqByID(qqeid);
		eqq.setT_e_eid(eid);
		eqq.setLastfp(new Date()); // 更新的时间戳
		Emps emp = findEmpByID(eid);
		emp.setQqe(eqq.getQqename());
		updtEmp(emp);

		return "{usr:'" + emp.getEname() + "',msg:'" + updtOssqq(eqq) + "'}";
	}

	//////////////////////// 企业qq管理 end

	@Override
	public List<Salary> listPageSalaries(Page<Salary> page, int dptID) {
		// TODO Auto-generated method stub
		return salDao.selectAtPageByDept(page, dptID);
	}

	@Override
	public String addSalary(Salary sal) {
		// TODO Auto-generated method stub
		return salDao.insert(sal) > 0 ? "添加成功" : "添加失败";
	}

	public Salary findSalaryByID(int sid) {
		return salDao.selectByID(sid);
	}
	
	//批量添加工资报表的数据
	public List<Salary> toBeAddSalarys(Integer depID, Emps emp) {
		if(depID==null) {
			depID = ddao.findEmpsDptID(emp.getEid());
		}
		
		return salDao.selectSalaryByDept(depID);
	}

	public String deleteSalary(int sid) {
		return salDao.deleteByPrimaryKey(sid) > 0 ? "删除成功" : "删除失败";
	}

	@Override
	@Transactional
	public String updtSalary(Salary sal) {
		// TODO Auto-generated method stub
		return salDao.updateByPrimaryKey(sal) > 0 ? "更新成功" : "更新失败";
	}

	public List<Emps> selectEmpswithDept() {
		return edao.selectDeptwithEmps();
	}

	public Integer findStuIDBysnameandClsName(String sn, String cname) {
		return stuDao.findStuIdByName_clsName(sn, cname);
	}

	public Integer findEmpIDByEname_deptName(String en, String dname) {
		return edao.findStuIdByName_clsName(en, dname);
	}

	@Transactional
	public List saveStuattendance(String filePath, Emps emp) {

		Map<String, List> datas = readKqRecords(filePath, emp);
		List msgList = datas.get("消息");
		// 1.校验数据库原有数据 ----》删除旧数据
		// 2. 完成考勤逻辑
		if (datas.get("学员") != null && datas.size() > 0) {
			List<Stuattendance> data = (List) datas.get("学员");
			for (Stuattendance stuattendance : data) {
				// 先校验数据记录是否存在，存在覆盖数据(删除)
				Integer kqID = stuKqinDao.findIDByDate_StuID(stuattendance.getOssstuid(),
						DbCommonMethod.isoFormat.format(stuattendance.getKqdate1()));
				if (kqID != null) {
					stuKqinDao.deleteByPrimaryKey(kqID);
					msgList.add("已覆盖 '" + stuDao.findStuNameByStuid(stuattendance.getOssstuid()) + "' 的["
							+ DbCommonMethod.isoFormat.format(stuattendance.getKqdate1()) + "]考勤信息.");
				}
				stuKqinDao.insert(stuattendance);
			}
		}

		if (datas.get("员工") != null && datas.size() > 0) {
			List<Empattendance> data = (List) datas.get("员工");
			for (Empattendance empattendance : data) {
				Integer kqID = empKqinDao.findIDByDate_EmpID(empattendance.getEmpid(),
						DbCommonMethod.isoFormat.format(empattendance.getKqdate1()));
				if (kqID != null) {
					msgList.add("已覆盖 '" + edao.selectByID(empattendance.getEmpid()).getEname() + "' 的["
							+ DbCommonMethod.isoFormat.format(empattendance.getKqdate1()) + "]考勤信息.");
				}
				empKqinDao.insert(empattendance);
			}
		}
		return msgList;
	}

	// 读取考勤信息
	private Map<String, List> readKqRecords(String filePath, Emps emp) {

		List<String> msgs = new ArrayList();

		Map<String, List> datas = new HashMap();
		List<Stuattendance> kqListStu = new ArrayList();
		List<Empattendance> kqListEmp = new ArrayList();

		Date beginDate = null;
		Date endDate = null;

		try {
			// POI文件
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));

			// 取得Excel文档
			HSSFWorkbook kqXls = new HSSFWorkbook(fs);

			// 取得"原 始 记 录 表"sheet
			HSSFSheet sheet0 = kqXls.getSheet("原 始 记 录 表");

			// 取得第2行 title
			HSSFRow row = sheet0.getRow(1);
			HSSFCell cell = row.getCell(0);
			String tmpStr0 = cell.getStringCellValue();
			String[] strs0 = tmpStr0.substring(tmpStr0.indexOf(":") + 1).split("-");
			// 统计时段
			beginDate = DbCommonMethod.sdf01.parse(strs0[0]);
			endDate = DbCommonMethod.sdf01.parse(strs0[1]);

			// 每个人的考勤占3行，从第3行开始
			int endRow = sheet0.getLastRowNum() + 1;

			// 考勤记录人数
			// System.out.println(endRow +" : "+(endRow-2)/3);
			Stuattendance tmpKq = null;
			Empattendance empKq = null;
			Integer stuNo = 0; // 学生编号
			String stuName; // 学生姓名
			String clzName; // 学生班级
			int readRowNum = 3; // 正在读的行数
			int day = 1; // 日期的day 1号，2号....
			int maxDay = 0; // 最大天数

			// 打卡有效日期数量
			row = sheet0.getRow(readRowNum); // row=3 第一个人的
			for (int i = 0; i < 31; i++) { // 这个月最大天数
				tmpStr0 = row.getCell(i).getStringCellValue();
				if (tmpStr0 != null && tmpStr0.length() > 0) {
					maxDay++;
				} else {
					break;
				}
			}

			readRowNum = 4; // 第一个学生的考勤解析
			Department dpt = null;
			//// 循环读取begin
			for (int j = 0; j < (endRow - 2) / 3; j++) { // 一个员工的考勤占3行
				row = sheet0.getRow(readRowNum - 2); // 处理学生ID
				cell = row.getCell(0);
				tmpStr0 = cell.getStringCellValue();
				// stuNo = Integer.parseInt(tmpStr0.substring(tmpStr0.indexOf(":") + 1,
				// tmpStr0.indexOf("姓名")).trim());

				stuName = tmpStr0.substring(tmpStr0.indexOf("姓名:") + 3, tmpStr0.indexOf("部门:")).trim();
				// System.out.println(row+"."+stuName);
				clzName = tmpStr0.substring(tmpStr0.indexOf("部门:") + 3).trim();

				// 判断是学生的考勤还是员工的考勤
				dpt = deptDao.selectByDepname(clzName);
				if (dpt != null) {
					// 员工
					row = sheet0.getRow(readRowNum);

					// 存储一个员工的考勤list
					String kaoqinDay = null;
					// 该考勤记录的员工ID
					stuNo = findEmpIDByEname_deptName(stuName, clzName);
					if (stuNo != null) {
						for (int i = 0; i < maxDay; i++) { // 读取有效的列

							cell = row.getCell(i);
							tmpStr0 = cell.getStringCellValue();
							if (tmpStr0 != null && tmpStr0.length() > 0) {
								// System.out.println(tmpStr0);
								// 封装考勤记录
								empKq = new Empattendance();

								empKq.setEmpid(stuNo);
								empKq.setEid(emp.getEid()); // 导入人

								kaoqinDay = (1900 + beginDate.getYear()) + "-" + (beginDate.getMonth() + 1) + "-"
										+ ((i + 1) < 10 ? "0" + (i + 1) : (i + 1));

								if (tmpStr0.length() > 8) {
									strs0 = tmpStr0.split(" ");
									empKq.setKqdate1(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[0]));
									empKq.setKqdate2(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[1]));

								} else {
									empKq.setKqdate1(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[0]));
								}

								// 考勤记录 ----> List
								kqListEmp.add(empKq);
							}
						}
					} else {
						msgs.add("[" + clzName + "]部门的员工：(" + stuName + ") 信息不完整，考勤记录不能导入.");
					}

				} else {
					// student
					//// 处理考勤记录
					row = sheet0.getRow(readRowNum);

					// 存储一个员工的考勤list
					String kaoqinDay = null;

					stuNo = findStuIDBysnameandClsName(stuName, clzName);

					if (stuNo != null) {

						for (int i = 0; i < maxDay; i++) { // 读取有效的列

							cell = row.getCell(i);
							tmpStr0 = cell.getStringCellValue();
							if (tmpStr0 != null && tmpStr0.length() > 0) {
								// System.out.println(tmpStr0);
								// 封装考勤记录
								tmpKq = new Stuattendance();

								tmpKq.setOssstuid(stuNo);
								tmpKq.setEid(emp.getEid());

								kaoqinDay = (1900 + beginDate.getYear()) + "-" + (beginDate.getMonth() + 1) + "-"
										+ ((i + 1) < 10 ? "0" + (i + 1) : (i + 1));

								if (tmpStr0.length() > 8) {
									strs0 = tmpStr0.split(" ");
									tmpKq.setKqdate1(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[0]));
									tmpKq.setKqdate2(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[1]));

								} else {
									tmpKq.setKqdate1(DbCommonMethod.sdf02.parse(kaoqinDay + " " + strs0[0]));
								}

								// 考勤记录 ----> List
								kqListStu.add(tmpKq);
							}
						}

					} else {
						// 系统尚未正确登记的学生
						msgs.add("[" + clzName + "]班级的学员：(" + stuName + ") 信息不完整，考勤记录不能导入");
					}

				}

				// 下一个人
				readRowNum += 3;
			}

			datas.put("学员", kqListStu);
			datas.put("员工", kqListEmp);
			datas.put("消息", msgs);
			///////// 循环读取end//////

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return datas;
	}

	public List<Empattendance> listEmpattendanceByEmpID_Mth(int empID, String mth) {
		// TODO Auto-generated method stub
		return empKqinDao.findAllByEmpid_Mth(empID, mth);
	}

	@Override
	public Empattendance findEmpattendanceByID(int kqid) {
		// TODO Auto-generated method stub
		return empKqinDao.selectByPrimaryKey(kqid);
	}

	@Override
	public String updateEmpattendance(Empattendance record) {
		// TODO Auto-generated method stub
		return empKqinDao.updateByPrimaryKey(record) > 0 ? "更新成功" : "更新失败";
	}

	////////////// 请假管理
	@Transactional
	public String saveQinjia(Empqinjia qj, float numOfDay, float isAfternoon) {

		int num = (int) numOfDay;
		java.util.Calendar c = java.util.Calendar.getInstance();
		qj.setSqjdate(new Date());
		qj.setSqjstate(1);
		// 处理下午请假
		if (isAfternoon > 0) {
			// 有半天
			c.setTime(qj.getSqjbegin());
			c.set(Calendar.HOUR_OF_DAY, 12);
			qj.setSqjbegin(c.getTime());
		}

		empQJDao.insert(qj);
		num = (int) Math.ceil(numOfDay);
		if (num > 1) { // 请假多天

			// 下午开始请
			for (int i = 1; i < num; i++) {
				c.setTime(qj.getSqjbegin());
				c.set(Calendar.HOUR_OF_DAY, 0);
				c.add(Calendar.DAY_OF_MONTH, 1);
				qj.setSqjbegin(c.getTime());
				if ((i == (num - 1)) && isAfternoon == 0 && num != numOfDay) {
					// 最后一天 而且 结束一天只请上午
					c.set(Calendar.HOUR_OF_DAY, 12);
					qj.setSqjend(c.getTime());
				}
				empQJDao.insert(qj);
			}
		}
		if (isAfternoon > 0 && num == numOfDay) {
			// 多半天
			c.setTime(qj.getSqjbegin());
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.add(Calendar.DAY_OF_MONTH, 1);
			qj.setSqjbegin(c.getTime());
			c.set(Calendar.HOUR_OF_DAY, 12);
			qj.setSqjend(c.getTime());
			empQJDao.insert(qj);
		}

		return "申请提交成功。";
	}

	public List<Empqinjia> listAYearEmpqinjia(int eid) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.add(c.MONTH, 1);
		Date end = c.getTime();

		c.add(c.MONTH, -12);
		return empQJDao.findAllAyearByEid(eid, c.getTime(), end);
	}

	public List<Empqinjia> listAYearDeptqinjia(int deptID) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.add(c.MONTH, 1);
		Date end = c.getTime();

		c.add(c.MONTH, -12);
		return empQJDao.findAllAyearBydDptid(deptID, c.getTime(), end);
	}

	@Transactional
	public String deleteEmpqinjia(int sqjid) {
		try {
			int eid = empQJDao.findEidBySqjid(sqjid);
			Date insertDate = empQJDao.findSqjdateBySqjid(sqjid);
			java.util.Calendar c = java.util.Calendar.getInstance();
			c.setTime(insertDate);
			c.add(c.SECOND, -1);
			Date d1 = c.getTime();
			c.add(c.SECOND, 2);
			Date d2 = c.getTime();
			// System.out.println(eid+" - "+d1 +" - " +d2);
			empQJDao.deleteEid_Sqjdate(eid, d1, d2);
		} catch (Exception e) {
			return "删除失败";
		}
		return "删除成功";
	}

	@Transactional
	public String spEmpqinjia(int speid, int sqjid, int sqjstate, String spnote) {
		try {
			int eid = empQJDao.findEidBySqjid(sqjid);
			Date insertDate = empQJDao.findSqjdateBySqjid(sqjid);
			java.util.Calendar c = java.util.Calendar.getInstance();
			c.setTime(insertDate);
			c.add(c.SECOND, -1);
			Date d1 = c.getTime();
			c.add(c.SECOND, 2);
			Date d2 = c.getTime();
			empQJDao.spQinjia(speid,sqjstate,spnote,eid,d1,d2);
		} catch (Exception e) {
			e.printStackTrace();
			return "审批失败";
		}
		return "审批成功";
	}

	 

}
